package com.framework.core.sqlfactory.sqlmapperproxyfactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.framework.core.myexception.NoSuchSqlException;
import com.framework.core.sqlfactory.jdbc.BasePreparestatement;
import com.framework.core.utils.SqlMappingUtils;

//生成jdk动态到代理(interface)
public class SqlMapperProxy implements InvocationHandler {

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		System.out.println("执行前");
		if (Object.class.equals(method.getDeclaringClass())) {
			try {
				return method.invoke(this, args);
			} catch (Throwable t) {
				t.printStackTrace();
			}
		} else {
			return run(method, args);
		}
		System.out.println("执行后");
		return null;
	}

	// 具体实现通过方法名绑定。
	public Object run(Method method, Object[] args) throws NoSuchSqlException {

		System.out.println("执行方法：-----" + method.getName() + "--------");

		String sqlNameSpace = method.getDeclaringClass().getName();
		String sql = (String) SqlMappingUtils.getSqlById(sqlNameSpace, method.getName());

		if (null == sql) {
			// 终止操作
			throw new NoSuchSqlException("没有找到对应的sql！");
		}

		// 测试
		// UserInformation userInformation=new UserInformation();
		// userInformation.setUserCode("hello");
		Object object= BasePreparestatement.doQuery(sql, args, method.getReturnType(), method.getGenericReturnType());
		return object;
	}

	// 获取生成的代理对象
	public Object getProxyInstance(Class<?> clazz) {
		Object newProxyInstance = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, this);
		return newProxyInstance;
	}

}
